<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Account;
use App\Models\Admin\AdminMenu;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Goods;
use App\Models\Admin\GoodsCategory;
use App\Models\Admin\GoodsRepertoryLog;
use App\Models\Admin\StockOrder;
use App\Models\Admin\StockOrderGoods;
use App\Models\Admin\Store;
use App\Models\Admin\StoreOrder;
use App\Tools\Images;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class IndexController extends BaseController
{
    /**
     * 后台主页
     * @return [type]
     */
    public function index()
    {
        # 代理商申请待审核
        $info['toAuditStore'] = Store::where(['status' => 0])->count();
        #发货订单待审核
        $info['toAuditOrder'] = StoreOrder::where(['order_status' => 1])->count();
        $info['total'] = $info['toAuditStore'] + $info['toAuditOrder'];

        $ids = AdminUser::getMyAuth($this->userArr['user_id']);
        $menu = AdminMenu::getMyTree($ids);
        $info['menus'] = $menu;
        return view('admin/index/index', $info);
    }

    /**
     * 主页欢迎页
     * @return
     */
    public function welcome()
    {
        $data  = Array();
        $start = date('Y-m-d').' 00:00:00';
        $end   = date('Y-m-d H:i:s',time());

        # 货款余额
        $whereOne[] = ['id', '>' , 10];
        $whereOne[] = ['account_type', '=', 1];
        $data['hk_balance'] = Account::where($whereOne)->sum('money');
        # 管理费余额
        $whereTwo[] = ['id', '>' , 10];
        $whereTwo[] = ['account_type', '=', 2];
        $data['glf_balance'] = Account::where($whereTwo)->sum('money');
        # 代理商总数量
        $data['store_count'] = Store::count();
        # 商品库存总量
        $goodsIds = Array();
        $data['goods_inventory'] = 0;
        $list = GoodsRepertoryLog::select('id','goods_id','goods_after_num')->orderBy('id','desc')->get()->toArray();
        foreach ($list as $val) {
            if (in_array($val['goods_id'],$goodsIds)) {
                continue;
            } else {
                $goodsIds[] = $val['goods_id'];
                $data['goods_inventory']+=$val['goods_after_num'];
            }
        }
        # 今日出库商品量
        $whereThr[] = ['so.created_at', '>=' , strtotime($start)];
        $whereThr[] = ['so.created_at', '<=' , strtotime($end)];
        $data['today_outbound'] = StockOrderGoods::from('stock_order_goods as sog')
                                  ->leftJoin('stock_order as so', 'so.id', '=', 'sog.order_id')
                                  ->where($whereThr)
                                  ->sum('sog.goods_number');

        return view('admin/index/welcome', ['data' => $data]);
    }

    /**
     * 获取分类统计
     */
    public function getNumberStatistic()
    {
        # 商品订单统计，最近7日商品订单量、出库量
        $start = 0;
        $end   = 0;
        $date = Array();
        $data = Array();
        for ($i=0; $i<=6; $i++){
            $tmp = Array();
            $tmp['start'] = date('Y-m-d 0:0:0' ,strtotime( '+' . ($i-6) .' days', time()));
            $tmp['end']   = date('Y-m-d 23:59:59' ,strtotime( '+' . ($i-6) .' days', time()));
            $date[$i]     = $tmp;
            if ($i == 0) {
                $start =$tmp['start'];
            }
            if ($i == 6) {
                $end =$tmp['end'];
            }
            $data['date'][] = date('Y/m/d' ,strtotime( '+' . ($i-6) .' days', time()));
        }
        # 已发货订单量
        $whereOne[] = ['created_at', '>=' , strtotime($start)];
        $whereOne[] = ['created_at', '<=' , strtotime($end)];
        $orderList  = StockOrder::where($whereOne)->select('id','created_at')->get()->toArray();
        $data['order_count'] = [0,0,0,0,0,0,0];
        foreach ($orderList as $key=>$val) {
            foreach ($date as $k=>$v) {
                if (strtotime($val['created_at']) >= strtotime($v['start']) && strtotime($val['created_at']) <= strtotime($v['end'])) {
                    $data['order_count'][$k]++;
                }
            }
        }
        # 已出库（发货）商品量
        $whereTwo[] = ['so.created_at', '>=' , strtotime($start)];
        $whereTwo[] = ['so.created_at', '<=' , strtotime($end)];
        $goodsList  = StockOrderGoods::from('stock_order_goods as sog')
            ->leftJoin('stock_order as so', 'so.id', '=', 'sog.order_id')
            ->where($whereTwo)
            ->select('sog.goods_number','so.created_at')
            ->get()
            ->toArray();
        $data['outbound_count'] = [0,0,0,0,0,0,0];
        foreach ($goodsList as $key2=>$val2) {
            foreach ($date as $k2=>$v2) {
                if (strtotime($val2['created_at']) >= strtotime($v2['start']) && strtotime($val2['created_at']) <= strtotime($v2['end'])) {
                    $data['outbound_count'][$k2]+=$val2['goods_number'];
                }
            }
        }

        # 商品分类统计
        $category = GoodsCategory::select('id','pid','cate_name')->get()->toArray();
        foreach ($category as &$val) {
            $val['value'] = 0;
            $val['name']  = $val['cate_name'];
        }
        $cateIds = array_column($category,'id');

        $goods = Goods::select('cate_id')->get()->toArray();
        foreach ($goods as $good) {
            $key = array_search($good['cate_id'],$cateIds);
            if ($key !== false) {
                $category[$key]['value']++;
            }
        }

        $tree = getTree($category);
        foreach ($tree as &$tr) {
            if (array_key_exists('son',$tr)) {
                foreach ($tr['son'] as $son) {
                    $tr['value']+=$son['value'];
                }
                unset($tr['son']);
            }
        }

        $data['name'] = array_column($tree,'cate_name');
        $data['data'] = $tree;

        successMsg($data);
    }

    /**
     * 退出登录
     */
    public function loginOut()
    {
        session::forget('adminUserToken');
        session()->save();
        redirect('/admin/login')->send();
    }

    // 上传图片
    public function imageUpload(Request $request)
    {
//        $name = $request->file('avatar')->getClientOriginalName();
        $image_url = Images::uploadImg($this->requestFile['file']);
        $returnData['image'] = IMAGE_URI . $image_url;
        /*$returnData['image'] = 'http://enccdn.herdsric.com/1561520325611.jpg';*/
        successMsg($returnData);
    }

    /**
     * layui富文本编辑器上传图片
     * @param Request $reques
     */
    public function layuiUploadImage(Request $reques)
    {
        $image_url = Images::uploadImg($this->requestFile['file']);
        $data['src'] = IMAGE_URI . $image_url;
        /*$data['src'] = 'http://enccdn.herdsric.com/1561520325611.jpg';*/

        $info = [
            'code' => 0,
            'msg'  => '上传成功',
            'data' => $data
        ];
        echo json_encode($info);
        exit();
    }
}
